/**
 * Author: vanganhit Description : Use for sedev_shopping
 */

/*
 * Common
 */
var shopping = {};

shopping.removeItem = function(formId, itemId, message) {
	var answer = confirm(message);
	if (answer) {
		var objid = document.getElementById("id");
		objid.value = itemId;
		sedev.submitForm(formId);
	}
};

shopping.renderPaging = function(divId) {
	var divTag = document.getElementById(divId);
	if(divTag == null){
		alert(divId + " is " + divTag);
		return;
	}
	var data = sedev.json_decode(divTag.innerHTML);
	divTag.innerHTML = "";
	if (data.totalRecord == '0'){
		return;
	}
	data.currentPage = parseInt(data.currentPage);
	data.pageSize = parseInt(data.pageSize);
	data.numDisplay = parseInt(data.numDisplay);
	
    var totalpage = parseInt(data.totalRecord / data.pageSize);
    if (data.totalRecord % data.pageSize > 0)
        totalpage += 1;
    if(data.currentPage < 0 )
    	data.currentPage = 1;
    if (data.currentPage > totalpage)
    	data.currentPage = totalpage;    
    
    var paging = "", next = "", pre = "";
    var pos_start, pos_end;
    
    url = data.action + "&shopping_page_manager=";
    if (data.numDisplay >= totalpage) {
        pos_start = 1;
        pos_end = totalpage;
    }else{
        var half = parseInt(data.numDisplay / 2);
        if (data.currentPage <= half) {
            pos_start = 1;
        }else {
            if (data.currentPage + half > totalpage) {
                pos_start = totalpage - numdisplay + 1;
            } else {
                pos_start = data.currentPage - half + 1;
            }
        }
        pos_end = numdisplay;
    }
    if ((data.currentPage - 1) > 0) {
        pre = "<a href='" + url + (data.currentPage - 1) + "' style='cursor: pointer; color: rgb(0, 102, 204);' class='pre' >Trước</a>";
        pre = pre + "&nbsp;";
    } else {
        pre = "<a class='pre' >Trước</a>";
        pre = pre + "&nbsp;";
    }    
    if ((data.currentPage + 1) <= totalpage) {
        next = "<a href='" + url + (data.currentPage + 1) + "' style='cursor: pointer; color: rgb(0, 102, 204);' class='next' >Sau</a>";
        next = "&nbsp;" + next;
    } else {
        next = "<a class='next' >Sau</a>";
        next = "&nbsp;" + next;
    }
    for (var i = 0; i < pos_end; i++) {
        if (i != 0) {
            paging += "&nbsp;-&nbsp;";
        }
        if (pos_start == data.currentPage) {
            paging += "<strong class='current'>" + pos_start + "</strong>";
        }else {
            paging += "<a href='" + url + pos_start + "' class='page' style='cursor: pointer; color: rgb(0, 102, 204);' >" + pos_start + "</a>";
        }
        pos_start++;
    }

    paging = pre + paging + next;
    divTag.innerHTML = paging;
    $("#"+divId).css("display","block");
};

/*
 * Business Type
 */
shopping.postFormBusinessType = function(formId) {
	var isSubmit = true;
	var title = document.getElementById("title");
	if (title.value == '') {
		isSubmit = false;
	}
	if (isSubmit) {
		sedev.submitForm(formId);
	}
};

/*
 * Business Type
 */
shopping.postFormCurrency = function(formId) {
	var isSubmit = true;
	var title = document.getElementById("title");
	if (title.value == '') {
		isSubmit = false;
	}
	if (isSubmit) {
		sedev.submitForm(formId);
	}
};


/*
 * Information Shop
 */
shopping.postFormInfoShop = function(formId) {
	var isSubmit = true;
	var title = document.getElementById("title");
	var ownername = document.getElementById("ownername");
	var email = document.getElementById("email");
	if (title.value == '') {
		isSubmit = false;
	}
	if (ownername.value == '') {
		isSubmit = false;
	}
	if (email.value == '') {
		isSubmit = false;
	}

	if (isSubmit) {
		sedev.submitForm(formId);
	}
};

/*
 * Product Group
 */
shopping.postFormProductGroup = function(formId) {
	var isSubmit = true;
	var title = document.getElementById("title");
	var attribute = document.getElementById("attribute");
	if (title.value == '') {
		isSubmit = false;
	}
	attribute.value = shopping.getAttribute('showAttribute');
	if (isSubmit) {
		sedev.submitForm(formId);
	}
};

shopping.addAtribite = function(displayId, inputId, title) {
	var inputHidden = document.getElementById(inputId);
	if (inputHidden != null) {
		if (inputHidden.value == '' || inputHidden.value == '0') {
			inputHidden.value = '1';
		} else {
			var num = parseInt(inputHidden.value);
			++num;
			inputHidden.value = num;
		}
		title = "<span>" + title + " " + inputHidden.value + " : " + "</span>";
	}
	var divInsert = "";
	divInsert += "<div class='add_attribute'>";
	divInsert += title;
	divInsert += "<input type='text' value='' size='50' />";

	divInsert += "</div>";
	$('#' + displayId).append(divInsert);
};

shopping.getAttribute = function(displayId) {
	var listDivDisplay = document.getElementById(displayId)
			.getElementsByTagName("div");
	var result = new Object();
	result['data'] = new Array();
	for ( var index = 0; index < listDivDisplay.length; ++index) {
		var item = new Object();
		var tagInput = listDivDisplay[index].getElementsByTagName('input');
		if (tagInput[0].value != '') {
			item["attribute"] = tagInput[0].value;
			result['data'][result['data'].length] = item;
		}
	}
	return sedev.json_encode(result);
};

shopping.parseAttribute = function(displayId, inputId, title) {
	var inputHidden = document.getElementById(inputId);
	var divObj = new Object();
	var divInsert = "";
	if (inputHidden != null && $('#' + displayId).html()!='') {		
		divObj = sedev.json_decode($('#' + displayId).html());
		var data = divObj.data;
		var count = 0;
		for ( var index = 0; index < data.length; ++index) {
			++count;
			var titleText = "<span>" + title + " " + count + " : " + "</span>";

			divInsert += "<div class='add_attribute'>";
			divInsert += titleText;
			divInsert += "<input type='text' value='" + data[index].attribute
					+ "' size='50' />";
			divInsert += "</div>";
		}
		inputHidden.value = count;		
	}
	$('#' + displayId).html(divInsert);
	$('#' + displayId).css("display", "block");
};

shopping.renderTreeView = function(divId, className, selectId) {
	var divData = document.getElementById(divId);
	var data;
	if (divData == null) {
		alert(id + " is " + divData);
		return;
	}
	data = sedev.json_decode(divData.innerHTML);
	var listData = data.data;

	var date = new Date();
	var ulRootId = "root_" + date.getTime();
	var ulRoot = "<ul id='" + ulRootId + "' class='root'>" + "</ul>";
	$(divData).html(ulRoot);
	$(divData).css('display', 'block');

	var index = 0;
	while (index < listData.length) {
		var parentItemId = "item" + listData[index].parentId + "_"
				+ date.getTime();
		var itemId = "item" + listData[index].id + "_" + date.getTime();
		var item = ""; // current item
		var ulChildId = "child_" + parentItemId; // id tag ul
		var classStyle = className;
		if(selectId == listData[index].id){
			classStyle += " current";
		}
		item = "<li id='" + itemId + "'>";
		item += "<span class='" + classStyle	+ "' name='" + listData[index].id + "'>" + listData[index].name	+ "</span>";
		item +="<div id='data_attribute"+listData[index].id+"' style='display:none'>" + listData[index].data + "</div>";		
		item += "</li>";

		if (listData[index].parentId == '0') {
			$('#' + ulRootId).append(item);
		} else {
			// tim parent id
			var $parentItem = $('#' + ulRootId).find('#' + parentItemId);
			var hasULChild = document.getElementById(ulChildId);
			if (hasULChild == null) {
				var ulChild = "<ul id='" + ulChildId + "' class='child' >" + "</ul>";
				$parentItem.append(ulChild);
			}
			// add child
			$parentItem.find('#' + ulChildId).append(item);
		}
		++index;
	}
};

shopping.eventClickGroupProduct = function(divId, className, inputId, displayId, inputAttribute, title) {
	$('#' + divId).find('.'+className).click(function() {
		$('#' + divId).find('.'+className).removeClass('current');
		$(this).addClass('current');
		var inputTag = document.getElementById(inputId);
		if (inputTag != null) {
			inputTag.value = $(this).attr('name');
		}
		$('#'+displayId).css("display","none");		
		$('#'+displayId).html($('#data_attribute'+$(this).attr('name')).html());		
		shopping.parseAttribute(displayId, inputAttribute, title);
	});
};

/*
 * Product Type
 */
shopping.postFormProductType = function(formId) {	
	var isSubmit = true;
	var title = document.getElementById("title");
	var businesstype = document.getElementById("businesstype");
	var groupproduct = document.getElementById("groupproduct");
	var attribute = document.getElementById("attribute");
	
	if(title == null || (title !=null && title.value == '')){
		alert("title");
		isSubmit = false;
	}
	if(businesstype == null || (businesstype !=null && businesstype.value == '0')){
		alert("businesstype");
		isSubmit = false;
	}
	if(groupproduct == null || (groupproduct !=null && groupproduct.value == '')){
		alert("groupproduct");
		isSubmit = false;
	}
	if(attribute == null){
		alert("attribute");
		isSubmit = false;
	}else{
		attribute.value = shopping.getAttribute('showAttribute');
	}
	if (isSubmit) {
		sedev.submitForm(formId);
	}
};

/*
 * Product
 */
shopping.postFormProduct = function(formId) {
	var isSubmit = true;
	var title = document.getElementById("title");
	var productcode = document.getElementById("productcode");
	var price = document.getElementById("price");
	var pricesale = document.getElementById("pricesale");
	
	/*var date = document.getElementById("date");
	date.value = shopping.getTimeFromInput('showdate');*/
	
	var attribute = document.getElementById("attribute");
	attribute.value = shopping.getAttributeProduct("showAttribute");
	
	var content = document.getElementById("productcontent");
	content.value = sedevShoppingProductContent.getHTML();
	
	var image = document.getElementById("productimage");
	image.value = shopping.getImageProduct(sedevShoppingProductImage.getHTML());
	
	if(title == null || (title !=null && title.value == '')){
		alert("title");
		isSubmit = false;
	}
	if(price == null || (price !=null && isNaN(parseInt(price.value)))){
		alert("price");
		isSubmit = false;
	}
	if(pricesale == null ){		
		alert("pricesale null");
		isSubmit = false;		
	}else{
		if(pricesale.value == ''){
			pricesale.value = '0';
		}else{
			if(isNaN(parseInt(pricesale.value))){
				alert("pricesale");
				isSubmit = false;	
			}
		}
	}	
	if (isSubmit) {
		sedev.submitForm(formId);
	}
};

shopping.checkProductCode = function(code){
	return false;
};

shopping.changeSelectProductType = function(self, displayId){
	$('#'+displayId).css("display","none");		
	$('#'+displayId).html($.trim($('#data_attribute'+self.value).html()));		
	shopping.parseAttributeProduct(displayId);
};

shopping.parseAttributeProduct = function(displayId){	
	var divObj = new Object();
	var divInsert = "";
	if ($('#' + displayId).html()!='') {		
		divObj = sedev.json_decode($('#' + displayId).html());
		var data = divObj.data;		
		for ( var index = 0; index < data.length; ++index) {			
			var titleText = "<span>" + data[index].attribute + "</span>" + " : ";
			divInsert += "<div class='product_attribute'>";
			divInsert += titleText;
			divInsert += "<input type='text' value='' size='50' />";
			divInsert += "</div>";
		}
	}
	$('#' + displayId).html(divInsert);
	$('#' + displayId).css("display", "block");
};

shopping.parseAttributeProductEdit = function(displayId){	
	var divObj = new Object();
	var divInsert = "";
	if ($('#' + displayId).html()!='') {		
		divObj = sedev.json_decode($('#' + displayId).html());
		var data = divObj.data;		
		for ( var index = 0; index < data.length; ++index) {
			for(var item in data[index]){
				var titleText = "<span>" + item + "</span>" + " : ";
				divInsert += "<div class='product_attribute'>";
				divInsert += titleText;
				divInsert += "<input type='text' value='" + data[index][item] + "' size='50' />";
				divInsert += "</div>";
			}
		}
	}
	$('#' + displayId).html(divInsert);
	$('#' + displayId).css("display", "block");
};

shopping.getAttributeProduct = function(displayId) {
	var listDivDisplay = document.getElementById(displayId)
			.getElementsByTagName("div");
	var result = new Object();
	result['data'] = new Array();
	for ( var index = 0; index < listDivDisplay.length; ++index) {
		var item = new Object();
		var tagInput = listDivDisplay[index].getElementsByTagName('input');
		var tagSpan = listDivDisplay[index].getElementsByTagName('span');
		item[tagSpan[0].innerHTML] = tagInput[0].value;
		result['data'][result['data'].length] = item;		
	}
	return sedev.json_encode(result);
};

shopping.getImageProduct = function(text) {
	var content = text;
	var result = new Object();
	result["large"] = new Array();
	var pos = -1;
	var link = "";
	var isAdd = false;
	while(content != ''){
		var item = new Object();
		item["link"]="";
		item["style"]="";
		pos = content.indexOf("<img");		
		if(pos > 0){
			content = content.substr(pos+4, content.length);
			pos = content.indexOf(">");
			if(pos > 0){
				var subcontent = content.substr(0, pos+1);
				
				// get style
				pos = subcontent.indexOf("style=");
				if(pos > 0){
					var textStyle = subcontent.substr(pos+6,subcontent.length);
					var c = textStyle.substr(0,1);					
					if(textStyle.length > 1){
						textStyle = textStyle.substr(1,textStyle.length);
						pos = textStyle.indexOf(c);
						if(pos > 0){
							item["style"] = textStyle.substr(0, pos);							
							isAdd = true;
						}
					}
				}
				
				// get link
				pos = subcontent.indexOf("src=");
				if(pos > 0){
					subcontent = subcontent.substr(pos+4, subcontent.length);
					if(subcontent.length > 0){
						var c = subcontent.substr(0,1);
						if(c == '"' || c == '\''){
							if(subcontent.length > 1){
								subcontent = subcontent.substr(1, subcontent.length);
								pos = subcontent.indexOf(c);
								if(pos > 0){																
									item['link'] = subcontent.substr(0, pos);
									isAdd = true;
								}
							}
						}
					}
				}
				content = content.substr(pos+2, content.length);
			}
		}else{
			content = '';
		}
		if(isAdd == true){
			result["large"][result["large"].length] = item;
			isAdd = false;
		}		
	}
	return sedev.json_encode(result);
};

shopping.insetImageProductToEditor = function(text) {
	var result = "";
	var data = sedev.json_decode(text);
	var listSmallLink = data.large;
	for(var index = 0; index<listSmallLink.length ; ++index){
		result += "<img ";
		result += "src='" + listSmallLink[index].link + "'";
		result += "style='" + listSmallLink[index].style + "'";
		result += "/>";
	}	
	return result;
};

shopping.addDateToInput = function(inputId ,milisecond){
	var tagInput = document.getElementById(inputId);
	if(tagInput != null){
		tagInput.value = sedev.getStringDateOfTime(milisecond);
	}
};
shopping.getTimeFromInput = function(inputId){
	var tagInput = document.getElementById(inputId);
	if(tagInput != null){
		return sedev.getTime(tagInput.value);
	}
	return 'error';
};

